using System;
using System.IO;
using System.Windows.Forms;
using Moonlite.UI.Shell.Controls;
using Moonlite.ExtensionApi.ControlInterfaces;
using Moonlite.ExtensionApi.GlobalInterfaces;
using Moonlite.Platform.General;
using Moonlite.Platform.Project;
using Moonlite.Platform.Text.File;

namespace Moonlite.UI.Shell.Wizards
{
    public partial class CreateFileWizard : Form, ICreateFileWizard
    {
        private TreeNode JassNode { get; set; }
        private TreeNode GalaxyNode { get; set; }

        public ITemplate Template { get; set; }
        public IProjectFile File { get; set; }
        public bool Result { get; set; }
        public bool DefaultFile { get; set; }
        private string ValidateError { get; set; }

        private bool ValidateOptions()
        {
            bool result = true;

            if (treeView.SelectedNode == null || treeView.SelectedNode == JassNode || treeView.SelectedNode == GalaxyNode)
            {
                ValidateError = "Invalid template selected.";
                result = false;
            }

            if (ProjectManager.IsInvalidFileName(textEditName.Text) == true)
            {
                ValidateError = "Invalid file name.";
                result = false;
            }

            if (string.IsNullOrEmpty(textEditName.Text) != true)
            {
                return result;
            }

            ValidateError = "You must enter a name for the project.";
            result = false;

            return result;
        }

        private TreeNode GetNode(TreeNode parent, string name)
        {
            if (parent != null)
            {
                TreeNode foundNode = null;
                foreach (TreeNode childNode in parent.Nodes)
                {
                    if (childNode.Text == name)
                    {
                        foundNode = childNode;
                        break;
                    }
                }

                if (foundNode != null) return foundNode;
                TreeNode node = new TreeNode(name);
                parent.Nodes.Add(node);
                return node;
            }
            else
            {
                TreeNode foundNode = null;
                foreach (TreeNode childNode in parent.Nodes)
                {
                    if (childNode.Text == name)
                    {
                        foundNode = childNode;
                        break;
                    }
                }

                if (foundNode != null) return foundNode;
                TreeNode node = new TreeNode(name);
                treeView.Nodes.Add(node);
                return node;
            }
        }

        private void PopulateTemplateList()
        {
            if (Global.Instance.Project == null) return;
            treeView.Nodes.Clear();
            GalaxyNode.Nodes.Clear();
            JassNode.Nodes.Clear();
            TemplateCollection templates = TemplateParser.GetAllTemplates();
            foreach (Template template in templates)
            {
                TreeNode projectTemplateNode = new TreeNode(template.Name) { Tag = template };

                if (template.Category.ToLower() == "galaxy" && Global.Instance.Project.Type == ProjectType.Galaxy)
                {
                    TreeNode categoryNode = GetNode(GalaxyNode, template.TemplateCategory);
                    categoryNode.Nodes.Add(projectTemplateNode);
                }
                else if (template.Category.ToLower() == "jass" && Global.Instance.Project.Type == ProjectType.Jass)
                {
                    TreeNode categoryNode = GetNode(JassNode, template.TemplateCategory);
                    categoryNode.Nodes.Add(projectTemplateNode);
                }
            }

            if (Global.Instance.Project.Type == ProjectType.Jass)
            {
                treeView.Nodes.Add(JassNode);
                JassNode.Expand();

                if (JassNode.Nodes.Count > 0)
                {
                    treeView.SelectedNode = JassNode.Nodes[0];
                    UpdateDescription();
                }
            }

            if (Global.Instance.Project.Type != ProjectType.Galaxy)
            {
                return;
            }

            treeView.Nodes.Add(GalaxyNode);
            GalaxyNode.Expand();

            if (GalaxyNode.Nodes.Count > 0)
            {
                treeView.SelectedNode = GalaxyNode.Nodes[0];
                UpdateDescription();
            }

            textEditName.SelectAll();
        }

        private void UpdateDescription()
        {
            labelDescription.Text = treeView.SelectedNode != GalaxyNode && treeView.SelectedNode != JassNode && treeView.SelectedNode.Tag != null ? (treeView.SelectedNode.Tag as Template).Description : "";
        }

        private void OnTreeViewNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            treeView.SelectedNode = e.Node;
            UpdateDescription();
        }

        private void OnOKClick(object sender, EventArgs e)
        {
            if (ValidateOptions() == true)
            {
                File = new ProjectFile() { Name = textEditName.Text };
                Template = treeView.SelectedNode.Tag as ITemplate;

                if (File.Name.EndsWith(String.Format(".{0}", Path.GetExtension(File.Name))) == true)
                {
                    File.Name = File.Name.Replace(String.Format(".{0}", Path.GetExtension(File.Path).Substring(1)), "");
                }

                AvailableProperties.FileName = File.Name;
                Result = true;
            }
            else
            {
                Result = false;
                ShowError(ValidateError);
            }

            if (Result == true)
            {
                Close();
            }
        }

        private void OnCloseClick(object sender, EventArgs e)
        {
            Result = false;
            Close();
        }

        private static void ShowError(string message)
        {
            MessageBox.Show(String.Format("Error while validating input: {0}", message), "Validating error",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }

        public new DialogResult ShowDialog()
        {
            PopulateTemplateList();
            textEditName.Text = "";
            if (DefaultFile == true)
            {
                if (Global.Instance.Project.Type == ProjectType.Jass)
                {
                    treeView.SelectedNode = JassNode.Nodes[0];
                }
                else
                {
                    treeView.SelectedNode = GalaxyNode.Nodes[0];
                }
            }

            return base.ShowDialog();
        }

        public CreateFileWizard()
        {
            InitializeComponent();
            Global.Instance.RegisterService(this, GetType().GetInterface("ICreateFileWizard"));
            labelDescription.Text = "";
            JassNode = new TreeNode("Jass");
            GalaxyNode = new TreeNode("Galaxy");
        }
    }
}